package main

import (
	"fmt"
	"net/http"
	"strings"
	"time"

	"gitee.com/kobeyyf/apibox/handler"
	"github.com/gorilla/websocket"
)

// https://www.01chain.com:9001/?AppCode=bus&Action=Say.Hello
func ActionSayHello(c *handler.Context) *handler.Response {
	return handler.NewSuccessResponse("hello world")
}
func ActionSleepSec(c *handler.Context) *handler.Response {
	fmt.Println(c.Request.RequestURI)
	time.Sleep(time.Second)
	return handler.NewSuccessResponse("hello world")
}

var upgrader = websocket.Upgrader{
	ReadBufferSize:  4096,
	WriteBufferSize: 1024,
	CheckOrigin: func(c *http.Request) bool {
		return true
	},
}

// ws=new WebSocket("wss://www.01chain.com:9001/?AppCode=bus&Action=Socket")
// ws=new WebSocket("ws://127.0.0.1:9001/?AppCode=bus&Action=Socket")
func ActionWebSocket(c *handler.Context) *handler.Response {
	ws, err := upgrader.Upgrade(c.ResponseWriter, c.Request, nil)
	if err != nil {
		logger.Error(err)
		return nil
	}
	defer ws.Close()

	ws.WriteMessage(websocket.TextMessage, []byte("action:param0,param1,..."))

	for {
		_, message, err := ws.ReadMessage()
		if err != nil {
			break
		}
		params := strings.SplitN(string(message), ":", 2)
		switch params[0] {
		case "close":
			ws.Close()
			return nil
		case "say":
			if len(params) != 2 {
				ws.WriteMessage(websocket.TextMessage, []byte("nothing"))
			}
			ws.WriteMessage(websocket.TextMessage, []byte(params[1]))
		default:
			ws.WriteMessage(websocket.TextMessage, []byte("unknow action"))
		}
	}

	return nil
}
